<?php
session_start();
require_once 'includes/Security.php';
require_once 'includes/User.php';
require_once 'includes/FileManager.php';

// 初始化安全设置
Security::secureSession();

$user = new User();
$fileManager = new FileManager();

// 检查用户是否已登录
if (!$user->isLoggedIn()) {
    header('Location: index.php');
    exit;
}

// 检查文件ID是否存在
if (!isset($_GET['id'])) {
    die('无效的请求');
}

$fileId = (int)$_GET['id'];
$fileInfo = $fileManager->getFileInfo($fileId, $user->getCurrentUser()['id']);

if (!$fileInfo) {
    die('文件不存在或无权访问');
}

$filePath = __DIR__ . '/uploads/' . $fileInfo['file_name'];

if (!file_exists($filePath)) {
    die('文件不存在');
}

// 设置下载头
header('Content-Type: ' . $fileInfo['file_type']);
header('Content-Disposition: attachment; filename="' . $fileInfo['original_name'] . '"');
header('Content-Length: ' . filesize($filePath));
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// 输出文件内容
readfile($filePath);
exit; 